import { ref } from 'vue';
import Papa from 'papaparse';

export default function useCsvReader() {
  const csvData = ref<any[]>([]);
  const csvHeaders = ref<string[]>([]);
  const csvFileName = ref<String>();
  const csvFileSize = ref<number>();

  const handleFileUpload = async (file: File | null) => {
    if (file) {
      try {
        const parsedData = await parseCsvFile(file);
        if (parsedData.length > 0) {
          csvHeaders.value = Object.keys(parsedData[0]);
        }
        csvFileName.value = file.name;
        csvFileSize.value = file.size;
        csvData.value = parsedData;
        console.log('csvData 的长度:', csvData.value.length);
        // console.log('Parsed CSV data:', csvData.value);
        // console.log('CSV Headers:', csvHeaders.value);
        // console.log(csvData.value[0]);
      } catch (error) {
        console.error('CSV parse error:', error);
      }
    }
  };

  async function parseCsvFile(file: File): Promise<any[]> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        const arrayBuffer = reader.result as ArrayBuffer;
        const uint8Array = new Uint8Array(arrayBuffer);

        // 将文件内容转换为字符串
        const textDecoder = new TextDecoder('gb2312');
        const text = textDecoder.decode(uint8Array);

        // 解析 CSV 内容
        Papa.parse(text, {
          header: true,
          complete: (results) => {
            resolve(results.data);
          },
          error: (error) => {
            reject(error);
          }
        });
      };
      reader.onerror = () => {
        reject(new Error('Failed to read file'));
      };
      reader.readAsArrayBuffer(file);
    });
  }

  return {
    csvFileName,
    csvHeaders,
    csvData,
    csvFileSize,
    handleFileUpload,
  };
}
